package cn.tutu.blockchain.controller;

import javax.validation.Valid;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.hibernate.validator.constraints.NotBlank;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageInfo;

import cn.tutu.blockchain.cktuser.service.CktUserService;
import cn.tutu.blockchain.common.MsgEnum;
import cn.tutu.blockchain.common.MsgObj;
import cn.tutu.blockchain.common.Page;
import cn.tutu.blockchain.exception.BusinessException;
import cn.tutu.blockchain.sysuser.entity.SysUser;
import cn.tutu.blockchain.sysuser.service.SysUserService;

@RestController
@Validated
@RequestMapping("/sysuser")
public class SysuserController {

	private static Logger LOGGER = LoggerFactory.getLogger(SysuserController.class);

	@Autowired
	private SysUserService sysUserService;
	
	@Autowired
	private CktUserService cktUserService;

	@RequestMapping("/ajaxLogin")
	public MsgObj ajaxLogin(String phone, String password) {
		LOGGER.info("登录:phone[{}],password[{}]", phone, password);
		MsgObj msg = MsgObj.buildSuccessMsg();

		UsernamePasswordToken token = new UsernamePasswordToken(phone, password);
		Subject subject = SecurityUtils.getSubject();

		subject.login(token);
		// 登录成功修改登录状态
		// SysUser sysuser = (SysUser) subject.getPrincipal();
		// sysuser.setLoginStatus(Boolean.TRUE);
		// sysUserService.updateLoginStatus(sysuser);
		SysUser user = (SysUser) subject.getPrincipal();
		user.setPassword(null);
		msg.setCode(MsgEnum.SUCCESS.getCode());
		msg.setMsg(MsgEnum.SUCCESS.getMessage());
		msg.setData(subject.getPrincipal());

		return msg;
	}

	@RequestMapping("/ajaxRegs")
	public MsgObj create(@Valid SysUser sysuser) {
		LOGGER.info("用户注册:phone[{}],verificationCode[{}],refPhone[{}]", sysuser.getPhone(),
				sysuser.getVerificationCode(), sysuser.getReferrerPhone());
		sysUserService.create(sysuser);
		return MsgObj.buildSuccessMsg();
	}

	@RequestMapping("/modify")
	@RequiresPermissions("sysuser[modify]")
	public MsgObj modify(SysUser sysUser) {
		LOGGER.info("用户修改:参数[{}]", sysUser.toString());
		sysUserService.update(sysUser);
		return MsgObj.buildSuccessMsg();
	}

	@RequestMapping("/modifyPwd")
	@RequiresPermissions("sysuser[modifyPwd]")
	public MsgObj modifyPwd(@Valid SysUser sysuser, @NotBlank(message = "原密码不可为空") String oldPwd) {
		LOGGER.info("用户修改密码:用户[{}],新密码[{}]", sysuser.getPhone(), sysuser.getPassword());
		sysUserService.updatePwd(sysuser, oldPwd);
		return MsgObj.buildSuccessMsg();
	}

	@RequestMapping("/resetPwd")
	@RequiresPermissions("sysuser[resetPwd]")
	public MsgObj resetPwd(@Valid SysUser sysuser) {
		LOGGER.info("用户重置密码:用户[{}],新密码[{}],验证码[{}]", sysuser.getPhone(), sysuser.getPassword(),
				sysuser.getVerificationCode());

		sysUserService.resetPwd(sysuser);
		return MsgObj.buildSuccessMsg();
	}

	@RequestMapping("/getUser")
	// @RequiresPermissions("sysuser[getUser]")
	public MsgObj getUserById(String id) {
		SysUser user = sysUserService.getUserById(id);
		return MsgObj.buildSuccessMsg(user);
	}

	@RequestMapping("/regEthId")
	public MsgObj regEthId(String ethId, @NotBlank(message = "电话不可为空") String phone) {
		try {
			LOGGER.info("注册ETH_ID:手机[{}],ETH_ID[{}]", phone, ethId);
			if (!StringUtils.isEmpty(ethId)) {
				//sysUserService.modifyEthIdByPhone(phone, ethId);				
				cktUserService.create(phone, ethId);
			} else {
				sysUserService.removeByPhone(phone);
			}
			return MsgObj.buildSuccessMsg();
		}catch(BusinessException e1) { 
			LOGGER.info("设置ETH_ID失败：", e1);
			return MsgObj.buildExceptionMsg(e1.getMessage());
		}catch (Exception e) {
			LOGGER.info("设置ETH_ID失败：", e);
			return MsgObj.buildExceptionMsg("系统异常,设置失败!");
		}

	}

	@RequestMapping("/setEthId")
	@RequiresPermissions("sysuser[setEthId]")
	public MsgObj setEthId(@NotBlank(message = "ethId不可为空") String ethId, @NotBlank(message = "电话不可为空") String phone) {
		try {
			LOGGER.info("设置ETH_ID:手机[{}],ETH_ID[{}]", phone, ethId);
			cktUserService.create(phone, ethId);
			//sysUserService.modifyEthIdByPhone(phone, ethId);

			return MsgObj.buildSuccessMsg();
		} catch (Exception e) {
			LOGGER.info("设置ETH_ID失败：", e);
			return MsgObj.buildExceptionMsg("系统异常,设置失败!");
		}

	}

	@RequestMapping("/getGridByRefPhone")
	public MsgObj getGridByRefPhone(@NotBlank(message = "电话不可为空") String refPhone, Page page) {
		PageInfo<SysUser> byModel = sysUserService.getByRefPhone(refPhone, page);
		return MsgObj.buildSuccessObj(byModel.getList());
	}

}
